package com.backend.system.service.processors.permission;

import com.backend.system.beans.permission.GrantPermissionToRoleReq;
import com.backend.system.common.annotation.ProcessorBean;
import com.backend.system.common.enums.ActionTypeEnum;
import com.backend.system.common.processor.AbstractProcessorTemplate;
import com.backend.system.common.processor.ProcessorContext;
import com.backend.system.dao.entity.RolePermission;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 角色分配权限处理器
 *
 * @author backend-manage
 */
@Slf4j
@Component
@ProcessorBean(action = ActionTypeEnum.ROLE_GRANT_PERMISSIONS)
public class GrantPermissionToRoleProcessor extends AbstractProcessorTemplate<GrantPermissionToRoleReq, Boolean> {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean handle(ProcessorContext<GrantPermissionToRoleReq> context) {
        GrantPermissionToRoleReq req = context.getData();
        Long roleId = req.getRoleId();
        List<Long> permissionIds = req.getPermissionIds();

        // 先删除角色对应的所有权限列表
        rolePermissionService.removeAllByRoleId(roleId);

        // 批量新增数据
        List<RolePermission> rolePermissions = new ArrayList<>();
        for (Long permissionId : permissionIds) {
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(roleId);
            rolePermission.setPermissionId(permissionId);
            rolePermissions.add(rolePermission);
        }

        return rolePermissionService.saveBatch(rolePermissions);
    }
}
